require 'fileutils'
require File.join(pwd, '../../../build/jake.rb')

def build_extension(name, arch)
  args = ['-o', 'Makefile', '-r', '-spec', $qmake_spec, "#{name}.pro", 'CONFIG-=debug', 'CONFIG+=release', $qmakevars]
  if (ENV['RHO_PLATFORM'] == 'osx')
      args = ['-o', 'Makefile', '-r', '-spec', $qmake_spec, "-early", "QMAKE_DEFAULT_LIBDIRS=$(xcrun -show-sdk-path)/usr/lib", "#{name}.pro", 'CONFIG-=debug', 'CONFIG+=release', $qmakevars]
  end
  puts Jake.run($qmake,args)
  fail "[qmake #{name}.pro]" unless $? == 0
  #puts Jake.run($make, ['clean'])
  fail "[make clean]" unless $? == 0
  if (ENV['RHO_PLATFORM'] == 'win32')
    puts Jake.run($make, ['release'])
  else
    puts Jake.run($make, ['all'])
  end
  fail "[make all]" unless $? == 0
end

namespace "build" do
  task :config do
    $rhoroot = ENV['RHO_ROOT']

    $targetdir = ENV['TARGET_TEMP_DIR']
    raise "TARGET_TEMP_DIR is not set" if $targetdir.nil?
    $tempdir = ENV['TEMP_FILES_DIR']
    $qmake = ENV['RHO_QMAKE']
    raise "RHO_QMAKE is not set" if $qmake.nil?
    $qmake_spec = ENV['RHO_QMAKE_SPEC']
    raise "RHO_QMAKE_SPEC is not set" if $qmake_spec.nil?
    raise "TEMP_FILES_DIR is not set" if $tempdir.nil?
    $qmakevars = ENV['RHO_QMAKE_VARS']

    $make = ENV['RHO_PLATFORM'] == 'osx' ? 'make' : 'nmake'
  end

  task :all => :config do
    build_extension('serialport', $arch)
  end
end

task :default => "build:all"
